(() => {
	let ele = {};
	ele.canjia = $('#canjia');
	ele.luxury = $('#luxury');
	ele.bm_num = $('#bm_num');
	ele.action_time = $('#action_time');
	ele.over_time = $('#over_time');
	ele.djs1 = $('#djs1');
	ele.djs2 = $('#djs2');
	ele.djs3 = $('#djs3');
	ele.open_time = $('#open_time');
	ele.jilu1 = $('#jilu1');
	ele.jilu2 = $('#jilu2');

	var countdownInterval //定时器
	var js

	

	var time_djs = null

	let is_enroll = 0;
	let ring_id = '';

	// 擂台争霸赛 获取游戏页面
	getMatch();
	function getMatch() {
		let token = getCookie("token");
		ajax({
			url: API_PATH.RING_BATTLE_INDEX,
			method: 'get',
			header: {
				'Authorization': token,
			},
			success: res => {
				if (res.code == 1) {
					ele.luxury.innerText = res.data.luxury
					ele.bm_num.innerText = res.data.enroll_num
					is_enroll = res.data.is_enroll;
					if(is_enroll == 2) {
						ele.canjia.innerHTML = '管家已报名'
					} else if(is_enroll == 1) {
						ele.canjia.innerHTML = '已报名'
					} else if(is_enroll == 0) {
						ele.canjia.innerHTML = '免费报名参加'
						// 免费参加
						ele.canjia.onclick = () => {
							baoming()
						}
					} else if(is_enroll == 3) {
						ele.canjia.innerHTML = '查看'
						ele.canjia.onclick = () => {
							location.href = '../page/attend_arena.html'
						}
					} else if(is_enroll == 4) {
						ele.canjia.innerHTML = '房东或管家已报名'
					}
					let count = res.data.next_enroll_time
					let count_1 = parseInt(res.data.next_enroll_time) + parseInt(3000)
					let count_2 = parseInt(res.data.next_enroll_time) + parseInt(3600)
					if (res.data.status == 0 || res.data.status == 3 || res.data.status == 4) {
						ele.djs1.style.display = 'block'
						ele.djs2.style.display = 'none'
						ele.djs3.style.display = 'none'
						time_djs = setInterval(() => {
							if (res.data.next_enroll_time <= 0) {
								clearInterval(time_djs);
								getMatch();
								return;
							}
							count--
							let day = parseInt(count / 60 / 60 / 24);
							day = day < 10 ? "0" + day : day;
							// 时
							let h = parseInt((count / 60 / 60) % 24);
							h = h < 10 ? "0" + h : h;
							// 分
							let m = parseInt((count / 60) % 60);
							m = m < 10 ? "0" + m : m;
							// 秒
							let s = parseInt(count % 60);
							s = s < 10 ? "0" + s : s;
							ele.action_time.innerHTML = `${day}天${h}时${m}分${s}秒`;
						}, 1000)
					} else if (res.data.status == 1) {
						ele.djs1.style.display = 'none'
						ele.djs2.style.display = 'block'
						ele.djs3.style.display = 'none'
						time_djs = setInterval(() => {
							if (res.data.next_enroll_time <= 0) {
								clearInterval(time_djs);
								return;
							}
							count_1--
							let day = parseInt(count_1 / 60 / 60 / 24);
							day = day < 10 ? "0" + day : day;
							// 时
							let h = parseInt((count_1 / 60 / 60) % 24);
							h = h < 10 ? "0" + h : h;
							// 分
							let m = parseInt((count_1 / 60) % 60);
							m = m < 10 ? "0" + m : m;
							// 秒
							let s = parseInt(count_1 % 60);
							s = s < 10 ? "0" + s : s;
							ele.over_time.innerHTML = `${day}天${h}时${m}分${s}秒`;
						}, 1000)
					} else if (res.data.status == 5) { // 等待活动开始时间
						ele.djs1.style.display = 'none'
						ele.djs2.style.display = 'none'
						ele.djs3.style.display = 'block'
						time_djs = setInterval(() => {
							if (res.data.next_enroll_time <= 0) {
								clearInterval(time_djs);
								ele.canjia.innerHTML = '查看'
								ele.canjia.onclick = () => {
									location.href = '../page/attend_arena.html'
								}
								return;
							}
							count_2--
							let day = parseInt(count_2 / 60 / 60 / 24);
							day = day < 10 ? "0" + day : day;
							// 时
							let h = parseInt((count_2 / 60 / 60) % 24);
							h = h < 10 ? "0" + h : h;
							// 分
							let m = parseInt((count_2 / 60) % 60);
							m = m < 10 ? "0" + m : m;
							// 秒
							let s = parseInt(count_2 % 60);
							s = s < 10 ? "0" + s : s;
							ele.open_time.innerHTML = `${day}天${h}时${m}分${s}秒`;
						}, 1000)
					}
					if(res.data.status == 3) {
						openTips('本局流局 重新开始')
					}
					// if(res.data.status == 4) {
					// 	openTips('本局结束')
					// }
					startWebSocket()
				} else openTips(res.msg || '未知错误');
			}
		});
	}

	let token = getCookie("token");
	// socket ws://rentwx.qunx.cc:2348   ws://fbsf.hfksh.cn:2347
	const wsuri = 'ws://rentwx.qunx.cc:2348?token=' + token

	let socket = null
	var timer
	let list = ''


	window.addEventListener('pageshow', function(event) {
		//event.persisted属性为true时，表示当前文档是从往返缓存中获取
		if (event.persisted) location.reload();
	});

	window.addEventListener('pagehide', function(event) {
		socket.close()
	});

	// 获取列表
	function getlist() {
		let data = {
			type: 'index',
			data: {}
		}
		socket.send(JSON.stringify(data))
	}

	// 链接websocket
	function startWebSocket() {
		socket = new WebSocket(wsuri)
		//监听消息接收事件
		socket.addEventListener('message', onMessage)

		//监听WebSocket连接事件
		socket.addEventListener('open', onOpen)

		//监听WebSocket异常事件
		socket.addEventListener('error', onError)

		//监听WebSockt关闭事件
		socket.addEventListener('close', onClose)
	}

	//监听WebSocket连接事件
	function onOpen() {
		// let id = getCookie('userid')
		// let data = {
		// 	type: 'login',
		// 	data: {
		// 		u_id: id
		// 	}
		// }
		// socket.send(JSON.stringify(data))
		heart()
	}

	// 设置心跳
	function heart() {
		clearInterval(timer);
		let data = {
			type: "pong",
			data: {}
		}
		timer = setInterval(() => {
			// 传递参数给服务器
			socket.send(JSON.stringify(data))
		}, 30000)
	}
	// getFinaListRecordsList();
	//监听WebSocket异常事件
	function onError(e) {
		console.error(e)
		startWebSocket()
	}
	//监听消息接收事件
	function onMessage(e) {
		if (!e) return
		// console.log(e.data)
		let data = JSON.parse(e.data)
		// console.log(data)

		switch (data.type) {
			case 'login':
				getlist(); // 绑定用户 发送u_id
				break;
			
			case 'error':
				openTips(data.msg)
				break;
			case 'enroll': // 报名
				openTips(data.msg)
				enroll(data.data)
				break;
			case 'enrot_end': // 报名结束
				getMatch();
				getFinaListRecordsList();
				break;
			case 'game_start': // 游戏开始
				getMatch();
				location.href = '../page/attend_arena.html';
				break;
			case 'change':
			    numchange(data.data)
			    break;
			case 'join_room': //开局后加入房间
				break;
			case 'attack': // 主动攻击
				break;
			case 'enroll_end': // 报名结束
				getMatch();
				break;
			case 'back':
				openTips(data.msg)
				break;
		}
	}

	//监听WebSockt关闭事件
	function onClose(e) {
		console.log('WebSocket disconnected.', e)
	}
	
	// 修改参与人数
	function numchange(data) {
		ele.bm_num.innerHTML = data.enroll_num
	}

	// 报名成功改变状态
	function enroll(data) {
		ele.canjia.innerHTML = '已报名'
	}

	// 报名事件
	function baoming() {
		let data = {
			type: 'enroll',
			data: {}
		}
		socket.send(JSON.stringify(data))
	}

	// 进行倒计时
	function daojishi(room_id) {
		let daojishi = $('#daojishi');
		let time = daojishi.getAttribute('data')
		// 每秒钟更新一次倒计时
		clearInterval(countdownInterval)
		countdownInterval = setInterval(() => {
			countdown(time, room_id)
		}, 1000)
	}

	// 倒计时逻辑
	function countdown(time, room_id) {
		let daojishi = $('#daojishi');
		// 当前时间戳（单位：毫秒）
		let currentTimestamp = new Date().getTime();
		// 计算剩余时间（单位：毫秒）
		let remainingTime = (time * 1000 + 180000) - currentTimestamp;
		var remainingMinutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
		var remainingSeconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
		daojishi.innerHTML = localStorage.getItem('remainingMinutes') + ':' + localStorage.getItem(
			'remainingSeconds')
		// 如果剩余时间小于等于0，则停止倒计时
		if (remainingSeconds < 10) {
			remainingSeconds = '0' + remainingSeconds
		}
		if (remainingTime <= 0) {
			clearInterval(countdownInterval);
			daojishi.innerHTML = '00:00';
			return;
		}
		// 计算剩余天数、小时数、分钟数、秒数
		// console.log(remainingMinutes, remainingSeconds);
		// 更新倒计时元素内容
		daojishi.innerHTML = remainingMinutes + ':' + remainingSeconds
	}
	
	
	
})()